#include "include/muduo/net/TcpServer.h"
#include "include/muduo/net/EventLoop.h"
#include "include/muduo/net/TcpConnection.h"
#include <memory>
#include <functional>
#include <iostream>
#include <unordered_map>

class TranslateServer
{
public:
    TranslateServer(uint16_t port)
        :_tcpserver(&_eventloop, muduo::net::InetAddress("0.0.0.0", port), "翻译服务器", muduo::net::TcpServer::kReusePort) //muduo::net::TcpServer::Option::kReusePort的区别
    {
        //注册这两个回调函数是核心
        _tcpserver.setConnectionCallback(std::bind(&TranslateServer::OnConnectionCallback, this, std::placeholders::_1));
        _tcpserver.setMessageCallback(std::bind(&TranslateServer::OnMessageCallback, this, std::placeholders::_1, 
                                                                                              std::placeholders::_2,
                                                                                              std::placeholders::_3));
    }
    void Start()
    {
        _tcpserver.start(); //这个主Reactor吗？监听新链接;
        _eventloop.loop();
    }
private:
    void OnConnectionCallback(const muduo::net::TcpConnectionPtr& conn) //链接建立与断开的时候会被调用
    {
        if(conn->connected())
            std::cout << "链接建立成功" << std::endl;
        else    
            std::cout << "链接断开" << std::endl;
    }
    std::string Transform(const std::string& str)
    {
        static std::unordered_map<std::string, std::string> dict = {
            {"apple", "苹果"},
            {"banana", "香蕉"},
            {"pear", "梨"}
        };
        auto iter = dict.find(str);
        if(iter == dict.end())
            return "没找到...";
        else return iter->second;
    }
    void OnMessageCallback(const muduo::net::TcpConnectionPtr& conn,
                            muduo::net::Buffer* buf,
                            muduo::Timestamp time)
    {
        std::string str = buf->retrieveAllAsString();
        std::string result = Transform(str);
        conn->send(result);
    }

private:
    muduo::net::EventLoop _eventloop;   //位置一定在上面，不然初始化_tcpserver会&nullptr
    muduo::net::TcpServer _tcpserver;
};


int main()
{
    std::unique_ptr<TranslateServer> svr = std::make_unique<TranslateServer>(8888);
    svr->Start();

    return 0;
}
